import redi_utils as utils
import redi_features as features

# TODO : Determine if we should really do all this...
def load(dataset_id, filename, config, options):
    print "Importing feature matrix from " + filename + " to " + dataset_id

    itemid = options.id
    if itemid is None: itemid = utils.get_filename(filename)

    outfile = open("%s/featurematrix/%s"%(dataset_id, itemid), "w")
    schema = process_feature_matrix(dataset_id, filename, outfile)
    outfile.close()

    return { "id": itemid, "type": "featurematrix", "table": itemid, "schema": schema }

def process_feature_matrix(dataset_label, matrix_file, outfile):
    feature_matrix_file = open(matrix_file)
    features_tracker = []

    feature_matrix_file.next()
    for line in feature_matrix_file:
        tokens = line.rstrip().split("\t")

        featureId = tokens[0]
        if (featureId in features_tracker):
            print "duplicated feature in feature set:" + featureId
        else:
            features_tracker.append(featureId)

            valuesArray = []
            alias = tokens[0]
            alias = alias.replace('|', '_')

            # TODO : This is shoving values into a cell... need better alternative
            data = alias.split(':')
            if len(data) > 4 and len(data[3]) > 3:
                data[3] = data[3][3:]
            if len(data) == 7:
                alias = alias + ":"
                data.append("")

            patient_values = ":".join(tokens[1:len(tokens)-1])
            for val in tokens[1:(len(tokens)-1)]:
                # TODO : Handling NAs?
                if (utils.is_numeric(val)):
                    valuesArray.append(float(val))
                else:
                    valuesArray.append(0.0)

            # TODO: Is this necessary?
            patient_value_mean = sum(valuesArray)/len(valuesArray)
            outfile.write(str(featureId) + "\t" + alias + "\t" + "\t".join(data) + "\t" + patient_values + "\t" + str(patient_value_mean) + "\n")

    schema = []
    schema.append({ "name": "FEATURE_ID", "label": "Feature ID", "type": "string" })
    schema.append({ "name": "ALIAS", "label": "Alias", "type": "string" })
    schema.append({ "name": "DATA", "label": "Data", "type": "string" })
    schema.append({ "name": "SAMPLE_VALUES", "label": "Sample Values", "type": "string" })
    schema.append({ "name": "MEAN_VALUE", "label": "Mean Value", "type": "double" })
    return schema